<template>
	<view class="content borrow">
		<topBar title='借钱' />
		<view>
			<image src="../../static/img/borrowBanner.png" mode="aspectFill" class="banner"></image>
		</view>
		<view class="cardsBlock">
			<view class="title"> 申请借款金额(元) </view>
			<view class="price"><input name="money" type="number" v-model="borrowMoney" :value="borrowMoney" @blur="blurHandle"
				 @input="setAmount" placeholder="" /> </view>

			<view class="lineNum">
				<view>{{utils.priceFormat(2000)}}</view>
				<view>{{utils.priceFormat(index2==1?quota=(totalMoney+2000)*0.8:zhong)}}</view>
			</view>
			<view class="progBox" id="progBox" @touchstart="touchStateHandle" @touchmove="touchmoveHandle" @touchend="touchendHandle">
				<view class="progressBar">
					<view :class="touch?'progress pos' : 'progress'" :style="position"></view>
				</view>
			</view>

		</view>
		<view class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">借款的标题</font><input name="borrowTitle" v-model="borrowTitle" :value="borrowTitle"
			 placeholder="请输入标题" />
		</view>
		<view class="itemsBlock clmargin">
			<ListItem class="selectItems" :des="borrowTerm + ' 个月'" title="借款期限" @click="showSinglePicker" /></button></view>

		<view class="itemsBlock clmargin">
			<picker @change="PickerChange" :value="index" :range="picker">
				<view class="picker">
					<ListItem class="selectItems" v-model="borrowPurpose" :des="picker[index]" title="借款用途" />
				</view>
			</picker>
		</view>
		<view class="itemsBlock clmargin" v-if="totalMoney !=0">
			<picker @change="typeChange" :value="index2" :range="typeList">
				<view class="typeList">
					<ListItem class="selectItems" v-model="borrowTypeName" :des="typeList[index2]" title="借款类型" />
				</view>
			</picker>
		</view>
		<view class="itemsBlock clmargin" v-if="totalMoney ==0">
			<picker @change="typeChange2" :value="index3" :range="typeList1">
				<view class="typeList">
					<ListItem class="selectItems" v-model="borrowTypeName2" :des="typeList1[index3]" title="借款类型" />
				</view>
			</picker>
		</view>
		<view v-if="index2==-1&&index3==-1" class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">利率</font><input name="borrowRate" type="number" v-model="borrowRate" :value="borrowRate"
			 placeholder="利率越高,借钱越快!" />
		</view>
		<view v-if="index2==0||index3==0" class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">利率</font><input name="borrowRate" type="number" v-model="borrowRate" :value="borrowRate"
			 placeholder="秒标:2%-15%" />
		</view>
		<view v-if="index2==1" class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">利率</font><input name="borrowRate" type="number" v-model="borrowRate" :value="borrowRate"
			 placeholder="净值标:5%-20%" />
		</view>
		<view v-if="index2==2||index3==1" class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">利率</font><input name="borrowRate" type="number" v-model="borrowRate" :value="borrowRate"
			 placeholder="抵押标:6%-20%" />
		</view>
		<view v-if="index2==3||index3==2" class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">利率</font><input name="borrowRate" type="number" v-model="borrowRate" :value="borrowRate"
			 placeholder="担保标:3%-15%" />
		</view>
		<view v-if="index2==4||index3==3" class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">利率</font><input name="borrowRate" type="number" v-model="borrowRate" :value="borrowRate"
			 placeholder="信用标:5%-20%" />
		</view>
		<view v-if="index2==3||index3==2" class="itemsBlock lineNum">
			<font size="2.5px" color="#787474">担保人</font><input name="guarantee" type="text" v-model="guarantee" :value="guarantee"
			 placeholder="担保人姓名" />
		</view>

		<view class="cu-bar bg-white margin-top" v-if="index2==2||index3==1">
			<view class="action">
				抵押物实照
			</view>
			<view class="action">
				{{imgList.length}}/4
			</view>
		</view>
		<view class="cu-form-group" v-if="index2==2 ||index3==1">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					<image :src="imgList[index]" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
						<text class='cuIcon-close'></text>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
					<text class='cuIcon-cameraadd'></text>
				</view>
			</view>
		</view>
		<view class="itemsBlock lineNum">
			<textarea maxlength="-1" :disabled="borrowContent!=null" @input="textareaAInput" v-model="borrowContent" placeholder="请输入借款说明"></textarea>
		</view>
		<view class="">
			<view class="labTitle" @tap="redioHandle"><label class="radio cl-main">
					<radio value="r2" class="redioCk" />我已阅读产品详情页面，知悉并接受产品申请条件及费用说
					明，并同意《借款相关协议》</label></view>
		</view>
		<view class="but">
			<ButtonItems :value="start == 1 ? '立即申请' : '审核中'" :type="subState && start == 1 ? 'big-blue' : 'big-gray'" @click="subState && start == 1 ? submitHandle(): ''" />
		</view>
		<selectItems :themeColor="themeColor" ref="mpvuePicker" :mode="mode" :deepLength="deepLength" :pickerValueDefault="pickerValueDefault"
		 @onConfirm="onConfirm" :pickerValueArray="pickerValueArray"></selectItems>
	</view>
</template>

<script>
	import topBar from '../../components/TopBar.vue'
	import ListItem from '../../components/ListItem.vue'
	import ButtonItems from '../../components/ButtonItems.vue'
	import selectItems from '../../components/selectItems.vue'

	export default {
		data() {
			return {
				picture:'',
				zhong: '',
				borrowTypeName2: '',
				guarantee: null, //担保人
				totalMoney: '', //是否借钱出去了，借了多少
				borrowRate: '',
				imgList: [],
				borrowContent: null,
				borrowTitle: '',
				borrowPurpose: '',
				borrowTypeName: '秒标',
				quota: 5000,
				statePosition: '',
				start: 1,
				endPosition: '',
				currentPosition: '',
				position: {
					width: '0px'
				},
				touch: false,
				borrowMoney: '2000',
				subState: false,
				borrowTerm: '6',
				description: '个人生活消费',
				themeColor: '#007AFF',
				mode: '',
				deepLength: 1,
				pickerValueDefault: [0],
				pickerValueArray: [],
				imgList: [],
				textareaAValue: '',
				textareaBValue: '',
				pickerSingleArray: [{
						label: '3',
						value: 3
					},
					{
						label: '6',
						value: 6
					},
					{
						label: '12',
						value: 12
					},
					{
						label: '24',
						value: 24
					}
				],
				index: -1,
				picker: ['个人消费', '商业融资', '房车贷', '其他'],
				index2: -1,
				typeList: ['秒标', '净值标', '抵押标', '担保标', '信用标'],
				index3: -1,
				typeList1: ['秒标', '抵押标', '担保标', '信用标']
			}
		},
		components: {
			topBar,
			ListItem,
			ButtonItems,
			selectItems,
		},
		onShow() {
			this.getquota()
			//this.getQualifications()
			if (this.quota.isIdCardAuth == 0) {
				this.goPath('/pages/user/identityAuth')
			}
		},
		onReady() {
			this.getElSize().then(res => {
				this.endPosition = res.width + this.statePosition
			})
		},
		onLoad() {
			this.getLoanMoney()
		},
		methods: {
			PickerChange(e) {
				this.index = e.detail.value
			},
			typeChange(e) {
				this.index2 = e.detail.value
			},
			typeChange2(e) {
				this.index3 = e.detail.value
			},
			goPath(url) {
				uni.navigateTo({
					url
				});
			},

			getQualifications() {
				this.request({
					url: `transaction/my/qualifications`,
					method: 'GET',
				}).then(res => {
					this.start = res.data.result
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: err.data.msg
					});
				})
			},
			submitHandle() {
				const data = {
					borrowMoney: this.borrowMoney,
					borrowTerm: this.borrowTerm,
					borrowPurpose: this.index,
					guarantee: this.guarantee,
					borrowRate: this.borrowRate,
					borrowContent: this.borrowContent,
					borrowTitle: this.borrowTitle,
					borrowTypeName: this.index2,
					borrowTypeName2: this.index3,
					list:this.imgList
				}
				this.request({
					url: `bidding/add`,
					method: 'POST',
					params: data
				}).then(res => {
					this.goPath('/pages/borrow/audit?title="申请成功"')
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: err.data.msg
					});
				})
			},
			ChooseImage() {
				const _this = this
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {

						const tempFilePaths = res.tempFilePaths;
						const uploadTask = uni.uploadFile({
							url: 'http://127.0.0.1:2020/file/file-up',
							filePath: tempFilePaths[0],
							name: 'file',

							success: function(uploadFileRes) {
								//alert(JSON.stringify(uploadFileRes))
								//alert((JSON.parse(uploadFileRes.data)).result)
								this.picture=(JSON.parse(uploadFileRes.data)).result
								_this.imgList = [..._this.imgList, (JSON.parse(uploadFileRes.data)).result]

							}
						});
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '靓仔',
					content: '确定要删除这张图片吗？',
					cancelText: '算了',
					confirmText: '非要删',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			showSinglePicker() {
				this.pickerValueArray = this.pickerSingleArray
				this.mode = 'selector'
				this.deepLength = 1
				this.pickerValueDefault = [0]
				this.$refs.mpvuePicker.show()
			},
			// 确定
			onConfirm(e) {
				this.borrowTerm = e.label
			},
			blurHandle() {
				if (this.borrowMoney < 2000) {
					this.borrowMoney = 2000
				}
			},
			textareaAInput(e) {
				this.textareaAValue = e.detail.value
			},
			setAmount(event) {
				const st = event.target.value
				this.borrowMoney = st
				if (Number(st) > Number(this.quota)) {
					uni.showToast({
						icon: 'none',
						title: '申请金额超出上限，请重新输入'
					});
					this.borrowMoney = this.quota
				}

				this.amountToPosition({
					st
				})
			},
			getquota() {
				this.request({
					url: `user/getUserInfo`,
				}).then(res => {
					//console.log(res)
					this.quota = res.data.result.quota
					this.zhong = res.data.result.quota
					uni.setStorage({
						key: 'quota',
						data: res.data.result.quota
					})
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: err.data.msg
					});
				})
			},
			getLoanMoney() {
				this.request({
					url: `bidding/lend/getLoanMoney`,
					method: 'GET'
				}).then(res => {
					this.totalMoney = res.data.result
					//alert(this.totalMoney)
				})
			},
			touchStateHandle(event) {
				this.statePosition = Number(event.currentTarget.offsetLeft)
				this.touch = true
				this.getElSize().then(res => {
					this.endPosition = Number(res.width) + this.statePosition
					this.setMovePosition(event.changedTouches[0].pageX)
				})
			},
			touchmoveHandle(event) {
				this.setMovePosition(event.changedTouches[0].pageX)
			},
			touchendHandle() {
				this.touch = false
			},
			setMovePosition(st, obj) {
				let wd = 0;
				let ps = st

				if (ps <= this.statePosition) {
					wd = 0
				} else if (ps >= this.endPosition) {
					wd = this.endPosition - this.statePosition
				} else {
					wd = st - this.statePosition
				}
				this.currentPosition = wd
				this.position = `width: ${wd}px`
				if (!obj) {
					this.amountToPosition({
						wd
					})
				}
			},
			amountToPosition({
				wd,
				st
			}) {
				if (wd) {
					let perc = wd / (this.endPosition - this.statePosition)
					let num = ((this.quota - 2000) * perc + 2000) / 100
					this.borrowMoney = num.toFixed(0) * 100
				} else if (st) {
					let perc = st / (this.quota - 2000)
					let num = (this.endPosition - this.statePosition) * perc
					this.setMovePosition(num, true)
				}

			},
			getElSize() { //得到元素的size
				return new Promise((res, rej) => {
					uni.createSelectorQuery().select("#progBox").fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						res(data);
					}).exec();
				})
			},
			redioHandle() {
				this.subState = true
			}
		}

	}
</script>
<style>
	@import "/colorui/main.css";
	@import "/colorui/icon.css";
</style>
<style lang="scss" scoped>
	.borrow {
		.banner {
			width: 723upx;
			height: 164upx;
			margin-top: 20upx;
			margin-left: 50%;
			transform: translateX(-50%);
		}

		.title {
			text-align: center;
			font-size: 28upx;
			line-height: 2;
			margin-bottom: 40upx;
		}

		.price {
			text-align: center;
			font-size: 64upx;
			margin-bottom: 40upx;
			color: $uni-color-primary;
		}

		.lineNum {
			color: $uni-text-color-grey;
			display: flex;
			justify-content: space-between;
		}

		.but {
			padding: 80upx;
		}

		.labTitle {
			margin-top: 30upx;
			font-size: 24upx;
			margin: 5px 20px 0px 20px;
			color: $uni-text-color-grey;
		}

		.redioCk {
			position: relative;
			top: -4upx;
			transform: scale(0.6);
		}

		.clmargin {
			padding: 0 30upx;
		}
	}

	.progBox {
		padding: 10upx 0upx;
	}

	.progressBar {
		position: relative;
		background: rgba(79, 87, 235, 0.5);
		height: 4upx;
		width: 100%;
	}

	.progress {
		position: absolute;
		content: '';
		left: 0upx;
		height: 4upx;
		width: 0;
		background: #4f57eb;
		// transition: 1ms;
	}

	.progress::before {
		position: absolute;
		content: '';
		top: -1px;
		right: 0upx;
		height: 8upx;
		width: 8upx;
		border-radius: 100%;
		background: #4f57eb;
	}

	.pos::before {
		position: absolute;
		content: '';
		top: -30upx;
		right: -30upx;
		height: 60upx;
		width: 60upx;
		border-radius: 100%;
		background: #4f57eb;
	}
</style>
